import styled from "styled-components";
import { BrowserRouter, Route, Routes, useNavigate } from "react-router-dom";
import { LockOutlined, UserOutlined } from "@ant-design/icons";
import { Button, Space, Spin, Input, Card, message } from "antd";
import React, { useState, useEffect } from "react";
import { login } from "../../services/user";
import { loginByExtension, hasExtension } from "../../services/polkadot-extension-handle";
import store from "../../utils/store";
import { loading, alert, confirm, notiError, notiOK, alertError } from "../../utils/antd-helper";
import * as oss from "../../services/oss";
import * as evm from "../../services/evm";
import { newAuthCode, updateAccount, applyInviteCode, initiateAuth, userLogin } from "../../services/graphql";


let lock = false;


const App = ({ className }) => {
	const navigate = useNavigate();
	const [status, setStatus] = useState("login");

	const [email, setEmail] = useState("");
	const [invitecode, setInvitecode] = useState("");
	const [vcode, setVcode] = useState("");

	const [remainSec, setRemainSec] = useState(0);
	const countDown = async s => {
		for (let i = 0; i < s; i++) {
			setRemainSec(s - i - 1);
			await sleep(1);
		}
	};
	const sleep = s => {
		return new Promise((resolve, reject) => {
			setTimeout(function () {
				resolve();
			}, s * 1000);
		});
	};

	useEffect(() => {
		let u = window.location.href;
		if (u.includes("/login?from=")) {
			let t = u.split("/login?from=")[1];
			if (t) {
				setInvitecode(t);
			}
		}
	}, []);
	const connectEvmWallet = async () => {
		try {
			if (lock) return;
			lock = true;
			loading('loading...');
			let ret = await evm.connectEvmWallet();
			lock = false;
			if (ret.msg != 'ok') {
				return alertError(ret.msg);
			}
			if (ret.data.login?.isFirstLogin) {
				if (invitecode) {
					return onApplyInviteCode();
				} else {
					return onSkipInviteCode();
				}
			}
			notiOK("Login success");
			navigate("/discover");
		} catch (e) {
			console.log(e);
		} finally {
			lock = false;
			loading();
		}
	}
	const onLoginByPolkadot = async () => {
		//check if has install extension
		try {
			let hasWallet = await hasExtension();
			if (!hasWallet) {
				message.error("Please install the polkadow extension.");
				let tmp = await confirm("Install polkadot extension now?");
				if (tmp) {
					window.open("https://polkadot.js.org/extension/");
				}
				return;
			}
			console.log('has wallet');
			if (lock) return;
			lock = true;
			let ret = await loginByExtension();
			lock = false;
			if (!ret || ret.msg != "ok") {
				return message.error(ret.msg);
			}
			notiOK("Login success");
			// loading("Querying balance...");
			// let balance = await oss.queryBalance();
			// console.log({ balance });
			// notiOK("Query balance success");
			// loading("Querying the space you have...");
			let space = await oss.territories();
			console.log({ space });
			// message.success("Login success.");
			// await getAccountType();
			if (ret.data.login?.isFirstLogin) {
				if (invitecode) {
					return onApplyInviteCode();
				} else {
					return onSkipInviteCode();
				}
			}
			navigate("/discover");
		} catch (e) {
			lock = false;
			console.log(e);
			message.error(e.message);
			loading();
		}
	};
	const onInputEmail = e => {
		setEmail(e.target.value);
	};
	const onInputVcode = e => {
		setVcode(e.target.value);
	};
	const onInputInvitecode = e => {
		setInvitecode(e.target.value);
	};
	const onLoginByEmail = async () => {
		if (!email) {
			return notiError("Please enter email");
		}
		const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
		if (!emailRegex.test(email)) {
			return notiError("Email format error");
		}
		if (lock) return;
		lock = true;
		loading("Loading...");
		let ret = await initiateAuth(email);
		loading();
		lock = false;
		notiOK("Auth code send success");
		setStatus("vcode");
		await countDown(60);
	};
	const onSendVCode = async () => {
		if (lock) {
			return message.error("Wait for a moment");
		}
		lock = true;
		loading("Loading...");
		let ret = await initiateAuth(email);
		loading();
		lock = false;
		notiOK("Auth code send success");
		await countDown(60);
	};
	const onValitVCode = async () => {
		if (!vcode) {
			return notiError("Please enter auth code");
		}
		if (lock) return;
		lock = true;
		loading("Loading...");
		let ret = await userLogin(email, vcode);
		loading();
		lock = false;
		if (!ret || ret.msg != "ok") {
			alertError(ret.msg);
			return;
		}
		notiOK("Login success");
		// await getAccountType();
		if (ret.data.login.isFirstLogin) {
			if (invitecode) {
				return onApplyInviteCode();
			} else {
				return onSkipInviteCode();
			}
		}
		navigate("/discover");
	};
	const onApplyInviteCode = async () => {
		let identity = email || store.get("addr");
		if (!invitecode) {
			navigate("/discover");
			return;
		}
		if (lock) return;
		lock = true;
		loading("Loading...");
		let ret = await applyInviteCode(identity, invitecode);
		loading();
		lock = false;
		if (!ret || ret.msg != "ok") {
			return;
		}
		// notiOK("Apply invite code success");
		await updateAccount({ isFirstLogin: 0 });
		navigate("/discover");
	};
	const onSkipInviteCode = async () => {
		if (lock) return;
		lock = true;
		await updateAccount({ isFirstLogin: 0 });
		lock = false;
		navigate("/discover");
	};
	return (
		<div className={className} style={{ backgroundImage: "url(" + process.env.PUBLIC_URL + "/img/login-bg.png)" }}>
			{/* <Space className="top-btns">
				<Button onClick={() => setStatus("login")}>login</Button>
				<Button onClick={() => setStatus("invitecode")}>invitecode</Button>
				<Button onClick={() => setStatus("skip")}>skip</Button>
				<Button onClick={() => setStatus("vcode")}>mail vcode</Button>
			</Space> */}
			<div className="con">
				{status == "login" ? <div className="goback-btn" onClick={() => navigate("/")}></div> : <div className="goback-btn" onClick={() => setStatus("login")}></div>}

				<img onClick={() => navigate("/")} className="img1" width={238} height={40} src={process.env.PUBLIC_URL + "/img/logo.png"} />
				<div onClick={() => navigate("/")} className="t1">
					Decentralized cloud storage
				</div>

				{status == "login" ? (
					<div className="box">
						<div className="t2">Log in with</div>
						<div className="t3" onClick={connectEvmWallet}>
							<img src={process.env.PUBLIC_URL + "/img/wallet-logo/rainbow.svg"} />
							<span>Rainbow Ethereum Wallet</span>
						</div>
						<div className="t3" onClick={onLoginByPolkadot}>
							<img src={process.env.PUBLIC_URL + "/img/wallet-logo/sub.svg"} />
							<span>SubWallet - Polkadot Wallet</span>
						</div>
						<div className="t4">or</div>
						<input value={email} className="input1" onChange={onInputEmail} onKeyUp={onInputEmail} onInput={onInputEmail} type="text" placeholder="Enter your email" />
						<div className="btn1" onClick={onLoginByEmail}>
							Sign up / Login
						</div>
					</div>
				) : status == "invitecode" ? (
					<div className="box vcode-box">
						<div className="t2-1">Enter the invitation code to get a 10% discount</div>
						<div className="t4">invite code</div>
						<input
							value={invitecode}
							className="input1"
							onChange={onInputInvitecode}
							onKeyUp={onInputInvitecode}
							onInput={onInputInvitecode}
							type="text"
							placeholder="Enter the code"
						/>
						<div className="btn1" onClick={onApplyInviteCode}>
							Proceed
						</div>
						<div className="link" onClick={() => setStatus("skip")}>
							skip
						</div>
					</div>
				) : status == "skip" ? (
					<div className="box skip-confirm-box">
						<div className="t2">Please pay attention</div>
						<div className="t2-1">Skipping this step will result in not being able to obtain 10% discount.</div>
						<div className="btn-room">
							<div className="btn-left" onClick={() => setStatus("invitecode")}>
								Fill in the invite code
							</div>
							<div className="btn-right" onClick={onSkipInviteCode}>
								Give up the discount
							</div>
						</div>
					</div>
				) : status == "vcode" ? (
					<div className="box auth-mail-box">
						<div className="t2-1">The auth code has been sent to {email}</div>
						<div className="t4">auth code</div>
						<input value={vcode} className="input1" type="text" onKeyUp={onInputVcode} onInput={onInputVcode} onChange={onInputVcode} placeholder="Enter the code" />
						{remainSec < 1 ? (
							<span className="send-btn send-btn-enable" onClick={onSendVCode}>
								send
							</span>
						) : (
							<span className="send-btn send-btn-disable">{remainSec}s</span>
						)}
						<div className="btn1" onClick={onValitVCode}>
							Proceed
						</div>
					</div>
				) : (
					""
				)}

				<div className="t5">
					<span>Powered by</span>
					<img width={80} height={25} src={process.env.PUBLIC_URL + "/img/cess-logo.png"} />
				</div>
			</div>
		</div>
	);
};
export default styled(App)`
	width: 100%;
	background-repeat: no-repeat;
	background-size: cover;
	display: block;
	overflow: hidden;
	.top-btns {
		position: fixed;
		top: 10px;
		left: 10px;
	}
	.con {
		width: 600px;
		height: 760px;
		border-radius: 30px;
		box-shadow: rgba(0, 0, 0, 0.35) 0px 0px 20px;
		background-color: rgb(255, 255, 255);
		overflow: hidden;
		display: flex;
		flex-direction: column;
		align-items: center;
		font-size: 14px;
		position: relative;
		top: 0;
		margin:70px auto 250px;
		.goback-btn {
			width: 100px;
			height: 100px;
			cursor: pointer;
			display: block;
			background-image: url(/img/back.svg);
			background-repeat: no-repeat;
			background-position: center;
			background-size: 30px;
			align-self: flex-start;
		}
		.img1 {
			width: 238px;
			height: 40px;
		}
		.t1 {
			font-size: 14px;
			color: rgb(195, 195, 195);
			line-height: 37px;
			margin-bottom: 5%;
		}
		.t2,
		.t4 {
			font-size: 20px;
			font-weight: bold;
			color: rgb(51, 51, 51);
			line-height: 58px;
			height: 58px;
		}
		.t3:hover {
			background-color: #eee;
		}
		.t3{
			width: 85%;
			border-radius: 50px;
			height: 50px;
			line-height: 50px;
			border: 1px solid rgb(195, 195, 195);
			color: #3b3b3b;
			cursor: pointer;
			display:flex;
			flex-direction: row;
			justify-content: center;
			align-items: center;
			margin:5px 0;
			font-weight: bold;
			font-size: 14px;
			position: relative;
			top:0;
			img{
				position: absolute;
				top:10px;
				left:40px;
				width:30px;
				height:30px;
				margin-right:10px;
				position: absolute;
			}
		}
		.input1 {
			width: 85%;
			border-radius: 48px;
			height: 48px;
			line-height: 48px;
			border: 1px solid rgb(195, 195, 195);
			text-align: center;
			outline: none;
			background-color: transparent;
		}
		.btn1 {
			border-radius: 48px;
			height: 48px;
			line-height: 48px;
			width: 190px;
			text-align: center;
			background-color: #000;
			color: #fff;
			margin-top: 38px;
			cursor: pointer;
		}
		.btn1:hover {
			background-color: rgb(49 48 48);
		}
		.link {
			text-decoration: underline;
			margin-top: 20px;
			cursor: pointer;
		}
		.btn-room {
			display: flex;
			overflow: hidden;
			flex-direction: row;
			align-items: center;
			justify-content: center;
			width: 100%;
			margin-top: 55px;
			div {
				width: 40%;
				margin: 0 3%;
				font-size: 14px;
				border-radius: 48px;
				height: 48px;
				line-height: 48px;
				text-align: center;
				cursor: pointer;
			}
			.btn-left {
				background-color: rgba(51, 51, 51, 1);
				border: 1px solid rgba(51, 51, 51, 1);
				color: #fff;
			}
			.btn-left:hover {
				background-color: #555;
			}
			.btn-right {
				background-color: #fff;
				border: 1px solid #aaa;
				color: #000;
			}
			.btn-right:hover {
				background-color: #eee;
			}
		}
		.t5 {
			display: flex;
			flex-direction: row;
			width: 100%;
			height: 50px;
			line-height: 50px;
			justify-content: center;
			align-items: center;
			margin-top: 130px;
			color: rgb(59, 59, 59);
			font-weight: bold;
			position: absolute;
			left: 0;
			bottom: 10px;
			span {
				margin-right: 20px;
			}
		}
		.box {
			width: 520px;
			display: flex;
			flex-direction: column;
			align-items: center;
			font-size: 14px;
			position: relative;
			top: 0;
			.send-btn {
				position: absolute;
				bottom: 96px;
				right: 45px;
				width: 80px;
				text-align: center;
				height: 30px;
				line-height: 30px;
				border-radius: 30px;
				display: block;
				overflow: hidden;
				font-size: 14px;
				color: #fff;
			}
			.send-btn-enable {
				background-color: rgba(51, 51, 51, 1);
				cursor: pointer;
			}
			.send-btn-disable {
				background-color: #bbbbbb;
				cursor: not-allowed;
			}
		}
		.vcode-box {
		}
		.skip {
		}
	}
`;
